package com.lagou.edu.dao.impl;

import com.lagou.edu.annotationt.Autowried;
import com.lagou.edu.annotationt.Service;
import com.lagou.edu.pojo.Account;
import com.lagou.edu.dao.AccountDao;
import com.lagou.edu.utils.ConnectionUtils;
import com.lagou.edu.utils.DruidUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @author 应癫
 */
@Service
public class JdbcAccountDaoImpl implements AccountDao {

    @Autowried
    private ConnectionUtils connectionUtils;


    public void init() {
        System.out.println("初始化方法.....");
    }

    public void destory() {
        System.out.println("销毁方法......");
    }

    @Override
    public Account queryAccountByCardNo(String cardNo) throws Exception {
        //从连接池获取连接
        // Connection con = DruidUtils.getInstance().getConnection();
        Connection con = connectionUtils.getCurrentThreadConn();
        String sql = "select * from account where cardNo=?";
        PreparedStatement preparedStatement = con.prepareStatement(sql);
        preparedStatement.setString(1,cardNo);
        ResultSet resultSet = preparedStatement.executeQuery();

        Account account = new Account();
        while(resultSet.next()) {
            account.setCardNo(resultSet.getString("cardNo"));
            account.setName(resultSet.getString("name"));
            account.setMoney(resultSet.getInt("money"));
        }

        resultSet.close();
        preparedStatement.close();
        //con.close();

        return account;
    }

    /**
     * 更新操作：
     * 注意：数据库事务归根到底是connection的事务
     * connection.commit()提交事务
     * connection.rollback();回滚事务
     * 问题分析：
     * 1.两次update使用两个数据库连接connection,这样的情况肯定不属于一个事务控制了。
     * 2.事务控制在dao层，没有在service层
     * 解决思路：
     * 1.两次update使用同一个数据库连接connection，可以用当前线程绑定一个connection，和当前线程有关的数据库操作都使用这个connection。
     * 2.事务控制在service层
     * @param account
     * @return
     * @throws Exception
     */
    @Override
    public int updateAccountByCardNo(Account account) throws Exception {

        // 从连接池获取连接
        // 改造为：从当前线程当中获取绑定的connection连接
        //Connection con = DruidUtils.getInstance().getConnection();
        Connection con = connectionUtils.getCurrentThreadConn();
        String sql = "update account set money=? where cardNo=?";
        PreparedStatement preparedStatement = con.prepareStatement(sql);
        preparedStatement.setInt(1,account.getMoney());
        preparedStatement.setString(2,account.getCardNo());
        int i = preparedStatement.executeUpdate();

        preparedStatement.close();
        //con.close();
        return i;
    }
}
